from django.shortcuts import render
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.contrib import auth
from django.core.context_processors import csrf

from django.contrib.auth.forms import UserCreationForm

from login.models import client

############ sign in form #########
def index(request):

    #obj_form = loginForm()

    #context = {'obj_form': obj_form}

    return render(request,'index.html')





def login(request):
    c = {}
    c.update(csrf(request))
    #return render_to_response('login.html',c)

    # use render not render_to .... to show css & java script
    return render(request,'login.html',c)

def auth_view(request):
    username = request.POST.get('username','')
    password = request.POST.get('password','')

    user = auth.authenticate(username=username, password=password)

    if user is not None:

        auth.login(request, user)
        request.session['username'] = username


        '''
        # to set username in session
        if request.session.test_cookie_worked():
            #request.session.delete_test_cookie()
            request.session.set_test_cookie()

        #return HttpResponseRedirect('/accounts/loggedin')
        # to go home page index page
        '''
        return HttpResponseRedirect('/login/')

    else:
        return HttpResponseRedirect('/accounts/invalid')

def loggedin(request):
    return render_to_response('loggedin.html',{'full_name':request.user.username})
    #return render_to_response('/login/index.html',{'full_name':request.user.username})

def invalid_login(request):
    return render_to_response('invalid_login.html')

def logout(request):

    del request.session['username']
    auth.logout(request)

    return render(request,'logout.html')


###############for registiration form####################

def register_user(request):

    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/accounts/register_success')


    args = {}
    args.update(csrf(request))

    args['form'] = UserCreationForm()
    print args

    #return render_to_response('register.html',args)
    return render(request,'register.html',args)


def register_success(request):

    #return render_to_response('register_success.html')
    return render(request,'register_success.html')












